import Mock from 'mockjs';
import { urls } from '../config';
import users from '../data/users';
import permissions from '../data/permission';
import pemissions from '../data/permission';
import menus from '../data/menus';
import { user } from '../data';
import { roles } from '../data';

const timeOut = 1200;

/**
 * 用户登录
 */
Mock.mock(urls.login, 'post', (request: any) => {
  const time = new Date().getTime();
  const token = `${time}QAZWSX`;

  const res = JSON.parse(request.body);
  if (res.username !== 'admin' || res.password !== 'admin') {
    return {
      status: 401,
      message: '账户名或密码错误（admin/admin)',
    };
  } else {
    return {
      status: 200,
      message: 'success',
      data: {
        // permissions: permissions,
        expired_at: Math.round(time / 1000) + timeOut,
        token: token,
      },
    };
  }
});

/**
 * 用户退出
 */
Mock.mock(urls.logout, 'get', (request: any) => {
  return {
    status: 200,
    message: request.body,
  };
});

/**
 * token 刷新
 */
Mock.mock(urls.refresh, 'get', () => {
  const time = new Date().getTime();
  const token = `${time}QAZWSX`;
  return {
    status: 200,
    message: 'success',
    data: {
      // permissions: permissions,
      expired_at: Math.round(new Date().getTime() / 1000) + timeOut,
      token: token,
    },
  };
});

// info
Mock.mock(urls.info, 'get', (request: any) => {
  return {
    status: 200,
    message: 'success',
    data: {
      menus: menus,
      permissions: [],
      user: user,
    },
  };
});

Mock.mock(urls.users, 'post', (request: any) => {
  const url = new URLSearchParams(request.url.split('?')[1]);

  const id = url.get('id');

  const user = JSON.parse(request.body);
  console.log(`mock:`, user);

  if (id == undefined) {
    return {
      status: 200,
      message: 'success',
      data: {
        id: 99,
        username: user.username,
        name: user.name,
        avatar: '',
        roles: user.roles,
        status: user.status,
        department: user.department,
        created_at: '2019-01-02 12:11:12',
      },
    };
  }
  return {
    status: 200,
    message: 'success',
    data: {
      id: parseInt(id),
      username: user.username,
      name: user.name,
      avatar: '',
      roles: user.roles,
      status: user.status,
      department: user.department,
      created_at: '2019-01-02 12:11:12',
    },
  };
});

// 获取用户
//users?page=1&pageSize=10&sortOrder=&sortField=
Mock.mock(RegExp(urls.users + '.*=.*'), 'get', (request: any) => {
  const url = new URLSearchParams(request.url.split('?')[1]);
  const page = parseInt(url.get('page') ?? '1');
  const pageSize = parseInt(url.get('pageSize') ?? '10');

  let items = users;
  //sort
  const sortField = url.get('sortField');
  const sortOrder = url.get('sortOrder') ?? '';
  if (sortField != null) {
    items.sort((a, b) => a[sortField].localeCompare(b[sortField]));
    if (sortOrder == 'descend') {
      items = items.reverse();
    }
  }

  //search
  const name = url.get('name');
  if (name != null && name != '') {
    items = items.filter((v) => v.name.includes(name));
  }

  const username = url.get('username');
  if (username != null && username != '') {
    items = items.filter((v) => v.username == username);
  }


  const total = items.length;
  // pagination
  items = items.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize);

  return {
    status: 200,
    message: 'success',
    data: {
      total: total,
      items: items,
    },
  };
});

// 权限
Mock.mock(RegExp(urls.pemissions + '.*'), 'get', (request: any) => {
  const url = new URLSearchParams(request.url.split('?')[1]);
  const userId = url.get('userId');

  if (userId != undefined) {
    return {
      status: 200,
      message: 'success',
      data: permissions.slice(0, 1),
    };
  }

  return {
    status: 200,
    message: 'success',
    data: permissions,
  };
});

// 获取菜单
//roles?page=1&pageSize=10&sortOrder=&sortField=
Mock.mock(RegExp(urls.roles + '.*'), 'get', (request: any) => {
  const url = new URLSearchParams(request.url.split('?')[1]);
  const page = parseInt(url.get('page') ?? '1');
  const pageSize = parseInt(url.get('pageSize') ?? '10');

  let items = roles.value;
  //sort
  const sortField = url.get('sortField');
  const sortOrder = url.get('sortOrder') ?? '';
  if (sortField != null) {
    items.sort((a, b) => a[sortField].localeCompare(b[sortField]));
    if (sortOrder == 'descend') {
      items = items.reverse();
    }
  }

  //search
  const name = url.get('name');
  if (name != null) {
    items = items.filter((v) => v.name.includes(name));
  }
  const total = items.length;
  // pagination
  items = items.slice((page - 1) * pageSize, (page - 1) * pageSize + pageSize);

  console.log('mock:', items);

  return {
    status: 200,
    message: 'success',
    data: {
      total: total,
      items: items,
    },
  };
});

// 创建/更新角色
Mock.mock(RegExp(urls.roles + '.*'), 'post', (request: any) => {
  const url = new URLSearchParams(request.url.split('?')[1]);

  const id = url.get('id');

  const data = JSON.parse(request.body);
  console.log(`mock:`, data);

  if (id == undefined) {
    return {
      status: 200,
      message: 'success',
      data: {
        id: 3,
        name: data.name,
        code: data.code,
      },
    };
  }
  return {
    status: 200,
    message: 'success',
    data: {
      id: parseInt(id),
      name: data.name,
      code: data.code,
    },
  };
});

Mock.mock(RegExp(urls.pemissions + '.*'), 'get', (request: any) => {
  const url = new URLSearchParams(request.url.split('?')[1]);
  const role = url.get('role');

  if (role != undefined) {
    return {
      status: 200,
      message: 'success',
      data: {
        菜单管理: ['MenuTable', 'P_MENU_UPDATE'],
        角色管理: ['RoleTable', 'P_ROLE_UPDATE', 'P_ROLE_CREATE', 'P_ROLE_PERMISSION'],
        用户管理: ['UserTable', 'P_USER_UPDATE', 'P_USER_CREATE'],
        基础组件: ['BasicComponent'],
        表单组件: ['FormComponent'],
        京东订单: ['JdOrder'],
      },
    };
  }

  return {
    status: 200,
    message: 'success',
    data: pemissions,
  };
});

// 获取菜单
Mock.mock(urls.menus, 'get', (request: any) => {
  return {
    status: 200,
    message: 'success',
    data: menus,
  };
});

// 菜单更新
Mock.mock(urls.menus, 'put', (request: any) => {
  return {
    status: 200,
    message: 'success',
  };
});
